package cn.klaw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import cn.klaw.config.AiProperties;
import cn.klaw.constants.AiConstants;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import cn.klaw.constant.MsgCode;
import cn.klaw.exception.DataException;
import cn.klaw.model.ai.AiFormModel;
import cn.klaw.service.OpenAiService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * OpenAi 实现类
 *
 *
 * @date 2024/10/9 14:39
 */
@Slf4j
@AllArgsConstructor
public class DefaultOpenAiServiceImpl implements OpenAiService {

    private OpenAiClient openAiClient;
    private AiProperties aiProperties;

    @Override
    public String completion(String prompt) {
        Message sendMessage = Message.builder().role(Message.Role.USER).content(prompt).build();
        ChatCompletion chatCompletion = getDefaultChatComletion(sendMessage);
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        return chatCompletionResponse.getChoices().stream().map(chatChoice -> chatChoice.getMessage().getContent()).collect(Collectors.joining());
    }

    @Override
    public String generatorModelStr(String businessName) {
        Message sysMessage = Message.builder().role(Message.Role.SYSTEM).content(AiConstants.GEN_MODEL_QUETION).build();
        String userTemplate = "当前业务需求是:";
        Message sendMessage = Message.builder().role(Message.Role.USER).content(userTemplate + businessName).build();

        ChatCompletion chatCompletion = getDefaultChatComletion(sysMessage, sendMessage);
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        return chatCompletionResponse.getChoices().stream().map(chatChoice -> chatChoice.getMessage().getContent()).collect(Collectors.joining());
    }

    @Override
    public List<AiFormModel> generatorModelVO(String prompt) {
        String result = "";
        List<AiFormModel> aiFormModels;
        try {
            result = generatorModelStr(prompt);
            aiFormModels = JSON.parseObject(result, new TypeReference<List<AiFormModel>>() {});
        } catch (Exception e){
            log.error("AI表单生成转换失败: {}, {}", result, e.getMessage());
            throw new DataException(MsgCode.SYS181.get());
        }
        return aiFormModels;
    }

    @Override
    public String completion(Message... messages) {
        ChatCompletion chatCompletion = getDefaultChatComletion(messages);
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        return chatCompletionResponse.getChoices().stream().map(chatChoice -> chatChoice.getMessage().getContent()).collect(Collectors.joining());
    }

    private ChatCompletion getDefaultChatComletion(Message... messages){
        AiProperties.ChatOption chatOption = aiProperties.getChat();
        return ChatCompletion.builder()
                .model(chatOption.getMode())
                .temperature(chatOption.getTemperature())
                .topP(chatOption.getTopP())
                .seed(chatOption.getSeed())
                .maxTokens(chatOption.getMaxTokens())
                .messages(Arrays.asList(messages)).build();
    }


}
